package com.zjw.nanyinge.service.impl;

import com.zjw.nanyinge.feign.WeChatApi;
import com.zjw.nanyinge.feign.WeChatFileApi;
import com.zjw.nanyinge.service.WeChatService;
import com.zjw.nanyinge.vo.resp.FileUploadRespVO;
import com.zjw.nanyinge.vo.resp.WeChatTokenRespVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {

    @Resource
    private WeChatApi weChatApi;
    @Resource
    private WeChatFileApi weChatFileApi;
    @Resource
    private CacheManager cacheManager;
    @Value("${weChat.appID}")
    private String appID;
    @Value("${weChat.appSecret}")
    private String appSecret;
    @Value("${weChat.grantType}")
    private String grantType;

    @Override
    public WeChatTokenRespVO getToken() {
        Cache weChatTokenCache = cacheManager.getCache("weChat");
        WeChatTokenRespVO weChatTokenRespVO = weChatTokenCache.get("weChatToken", WeChatTokenRespVO.class);
        if (Objects.isNull(weChatTokenRespVO)) {
            weChatTokenRespVO = weChatApi.getToken(appID, appSecret, grantType);
            weChatTokenRespVO.setExpiresDate(LocalDateTime.now().plusSeconds(weChatTokenRespVO.getExpires_in() - 60));
            weChatTokenCache.put("weChatToken", weChatTokenRespVO);
            log.info("缓存获取token：{}", weChatTokenRespVO.getAccess_token());
            return weChatTokenRespVO;
        }
        LocalDateTime expiresDate = weChatTokenRespVO.getExpiresDate();
        if (LocalDateTime.now().isAfter(expiresDate)) {
            weChatTokenCache.evict("weChatToken");
            return getToken();
        }
        log.info("缓存获取token：{}", weChatTokenRespVO.getAccess_token());
        return weChatTokenRespVO;
    }

    public FileUploadRespVO fileUpload(String type, MultipartFile media) {
        WeChatTokenRespVO token = getToken();
        return weChatFileApi.fileUpload(token.getAccess_token(), type, media);
    }

}
